package com.ctgu.tengyun.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.List;

@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@MapperScan(basePackages = DataSourcEelectricConfig.PACKAGE_PATH, sqlSessionFactoryRef = DataSourcEelectricConfig.SQL_SESSION_FACTORY)
public class DataSourcEelectricConfig {

    public final static String DATA_SOURCE_NAME = "dataSourceElectric";
    public final static String PACKAGE_PATH = "com.ctgu.tengyun.dao.mybatis";
    public final static String SQL_SESSION_FACTORY = "sqlSessionFactoryElectric";
    public final static String TX_MANAGER = "txManagerElectric";
    public final static List<String> XML_PATHS = Arrays.asList("classpath*:mybatis/*.xml");

    private static final Logger logger = LoggerFactory.getLogger(DataSourcEelectricConfig.class);

    @Value("${database.electric.url}")
    private String url;
    @Value("${database.electric.username}")
    private String username;
    @Value("${database.electric.password}")
    private String password;

    //按需添加
    @Value("${mybatis.config.path}")
    private String configPath;

    @Bean(name = DATA_SOURCE_NAME)
    public DataSource getDataSource() {
        return MybatisDataSourceConfigHelper.createDruidDataSource(url, username, password);
    }

    @Bean(name = TX_MANAGER)
    public DataSourceTransactionManager getTransactionManager(@Qualifier(value = DATA_SOURCE_NAME) DataSource dataSource) {
        return MybatisDataSourceConfigHelper.getTransactionManager(dataSource);
    }

    @Bean(name = SQL_SESSION_FACTORY)
    public SqlSessionFactory getSqlSessionFactoryData(@Qualifier(value = DATA_SOURCE_NAME) DataSource dataSource) {
        return MybatisDataSourceConfigHelper.getSqlSessionFactoryData(XML_PATHS, configPath, dataSource);
    }
}